package com.have.blog.xo.service.admin.impl;

import com.github.pagehelper.PageHelper;

import com.have.blog.base.enums.BlogStatus;
import com.have.blog.commons.feign.PictureFeignClient;
import com.have.blog.model.api.CommonPage;
import com.have.blog.model.mapper.TBlogMapper;
import com.have.blog.model.mapper.TPictureMapper;
import com.have.blog.model.mapper.TPictureSortMapper;
import com.have.blog.model.models.*;
import com.have.blog.utils.MyStringUtils;
import com.have.blog.utils.ResultUtils;
import com.have.blog.xo.constant.MessageConstant;
import com.have.blog.xo.constant.SysConstant;
import com.have.blog.xo.service.admin.AdminBlogService;
import com.have.blog.xo.service.admin.AdminPictureService;
import com.have.blog.xo.service.admin.AdminPictureSortService;
import com.have.blog.xo.uitls.WebUtil;
import com.have.blog.xo.vo.AdminPictureVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
@SuppressWarnings("all")
public class AdminPictureServiceImpl implements AdminPictureService {
    @Autowired
    private TPictureMapper pictureMapper;
    @Autowired
    private WebUtil webUtil;
    @Autowired
    private TBlogMapper blogMapper;
    @Autowired
    private TPictureSortMapper pictureSortMapper;
    @Autowired
    private PictureFeignClient pictureFeignClient;

    @Override
    public String getPageList(AdminPictureVo pictureVO) {
        PageHelper.startPage(pictureVO.getCurrentPage(), pictureVO.getPageSize());
        TPictureExample example = new TPictureExample();
        TPictureExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(pictureVO.getKeyword()) && !StringUtils.isEmpty(pictureVO.getKeyword().trim())) {
            criteria.andPicNameLike("%" + pictureVO.getKeyword() + "%");
        }
        criteria.andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andPictureSortUidEqualTo(pictureVO.getPictureSortUid());
        example.setOrderByClause("create_time desc");
        List<TPicture> pictureList = pictureMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(pictureList)) {
            return ResultUtils.successWithData(CommonPage.restPage(new ArrayList<TPicture>()));
        }
        // 拼接文件名
        StringBuilder sb = new StringBuilder();
        pictureList.forEach(item -> {
            if (!StringUtils.isEmpty(item.getFileUid())) {
                sb.append(item.getFileUid() + SysConstant.FILE_SEGMENTATION );
            }
        });

        String pictureResult = null;
        Map<String, String> pictureMap = new HashMap<>();
        if (!StringUtils.isEmpty(sb.toString())) {
            pictureResult = this.pictureFeignClient.getPicture(sb.toString(), SysConstant.FILE_SEGMENTATION);
        }
        List<Map<String, Object>> picList = webUtil.getPictureMap(pictureResult);
        picList.forEach(item -> {
            pictureMap.put(item.get(SysConstant.UID).toString(), item.get(SysConstant.URL).toString());
        });
        for (TPicture picture : pictureList) {
            if (!StringUtils.isEmpty(picture.getFileUid())) {
                picture.setPictureUrl(pictureMap.get(picture.getFileUid()));
            }
        }
        return ResultUtils.successWithData(CommonPage.restPage(pictureList));
    }

    @Transactional
    @Override
    public String addPicture(List<AdminPictureVo> pictureVOList) {
        List<TPicture> pictureList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(pictureVOList)) {
            // TODO 修改批量插入，事务效率太低
            for (AdminPictureVo item : pictureVOList) {
                TPicture picture = new TPicture();
                picture.setUid(MyStringUtils.getUUID());
                picture.setFileUid(item.getFileUid());
                picture.setPictureSortUid(item.getPictureSortUid());
                picture.setPicName(item.getPicName());
                picture.setStatus(BlogStatus.ENABLE.getStatus());
                picture.setCreateTime(new Date());
                picture.setUpdateTime(new Date());
                pictureMapper.insert(picture);
                pictureList.add(picture);
            }
        } else {
            return ResultUtils.errorWithMessage(MessageConstant.INSERT_FAIL);
        }
        return ResultUtils.successWithMessage(MessageConstant.INSERT_SUCCESS);
    }

    @Transactional
    @Override
    public String editPicture(AdminPictureVo pictureVO) {
        TPicture picture = pictureMapper.selectByPrimaryKey(pictureVO.getUid());
        if (picture == null) {
            return ResultUtils.errorWithMessage(MessageConstant.THE_PICTURE_NOT_EXIST);
        }
        TBlogExample blogExample = new TBlogExample();
        blogExample.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andFileUidEqualTo(pictureVO.getFileUid());
        List<TBlog> blogList = blogMapper.selectByExample(blogExample);
        // TODO BatchUpdate
        if (!CollectionUtils.isEmpty(blogList)) {
            blogList.forEach(item -> {
                item.setFileUid(picture.getFileUid());
                blogMapper.updateByPrimaryKeySelective(item);
            });
            Map<String, Object> map = new HashMap<>();
            map.put(SysConstant.COMMAND, SysConstant.EDIT_BATCH);

            // TODO 发送消息到RabbitMq

        }
        picture.setFileUid(pictureVO.getFileUid());
        picture.setPicName(pictureVO.getPicName());
        picture.setPictureSortUid(pictureVO.getPictureSortUid());
        picture.setUpdateTime(new Date());
        pictureMapper.updateByPrimaryKeySelective(picture);
        return ResultUtils.successWithMessage(MessageConstant.UPDATE_SUCCESS);
    }

    @Override
    public String deleteBatchPicture(AdminPictureVo pictureVO) {
        String uids = pictureVO.getUid();
        if (StringUtils.isEmpty(uids)) {
            return ResultUtils.errorWithMessage(MessageConstant.PARAM_INCORRECT);
        }
        List<String> uidList = MyStringUtils.changeStringToStringList(uids, SysConstant.FILE_SEGMENTATION);
        TPictureExample example = new TPictureExample();
        example.createCriteria()
                .andStatusEqualTo(BlogStatus.ENABLE.getStatus())
                .andUidIn(uidList);
        TPicture template = new TPicture();
        template.setUpdateTime(new Date());
        template.setStatus(BlogStatus.DISABLE.getStatus());
        pictureMapper.updateByExampleSelective(template, example);
        return ResultUtils.successWithMessage(MessageConstant.DELETE_SUCCESS);
    }

    @Override
    public String setPictureCover(AdminPictureVo pictureVO) {
        TPictureSort pictureSort = pictureSortMapper.selectByPrimaryKey(pictureVO.getPictureSortUid());
        if (pictureSort != null) {
            TPicture picture = pictureMapper.selectByPrimaryKey(pictureVO.getUid());
            if (picture != null) {
                pictureSort.setFileUid(picture.getFileUid());
                pictureSort.setUpdateTime(new Date());
                pictureSortMapper.updateByPrimaryKeySelective(pictureSort);
            } else {
                return ResultUtils.errorWithMessage(MessageConstant.THE_PICTURE_NOT_EXIST);
            }
        } else {
            return ResultUtils.errorWithMessage(MessageConstant.THE_PICTURE_SORT_NOT_EXIST);
        }
        return ResultUtils.successWithMessage(MessageConstant.UPDATE_SUCCESS);
    }
}
